package com.sunlg.smarthome.ui.environment;

import android.graphics.Color;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.sunlg.smarthome.R;
import com.sunlg.smarthome.base.BaseActivity;
import com.sunlg.smarthome.contract.TempHumContract;
import com.sunlg.smarthome.contract.presenter.TempHumPresenter;
import com.sunlg.smarthome.data.entity.Humidity;
import com.sunlg.smarthome.data.entity.Temperature;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

public class TempAndHumActivity extends BaseActivity implements TempHumContract.View{

    @BindView(R.id.cv_temp)
    CardView cvTemp;
    @BindView(R.id.cv_hum)
    CardView cvHum;
    @BindView(R.id.lc_temp_trend)
    LineChart lcTempTrend;
    @BindView(R.id.lc_hum_trend)
    LineChart lcHumTrend;

    private List<Temperature> temperatureList;
    private List<Humidity> humidityList;

    private TempHumContract.Presenter presenter;
    private LineData timeLineData;
    private LineData humLineData;

    private int deviceId;

    @Override
    protected int getLayoutResourceId() {
        return R.layout.activity_envir_model;
    }

    @Override
    protected void setupToolBar(Toolbar toolbar) {
        super.setupToolBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle("温湿度变化情况");
        actionBar.setDisplayHomeAsUpEnabled(true);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doFinish();
            }
        });
    }

    @Override
    protected void init() {
        deviceId = getIntent().getIntExtra("deviceId", 0);

        temperatureList = new ArrayList<>();
        humidityList = new ArrayList<>();

        presenter = new TempHumPresenter();
        presenter.attachView(this);

        timeLineData = new LineData();
        humLineData = new LineData();
    }

    @Override
    protected void initView() {
        initTempChart();
        initHumChart();
    }

    @Override
    public void hideTempChart() {
        if(cvTemp.getVisibility() != View.INVISIBLE){
            cvTemp.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void hideHumChart() {
        if(cvHum.getVisibility() != View.INVISIBLE){
            cvHum.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void showError(String msg) {
        toast(msg);
    }

    @Override
    protected void onStart() {
        super.onStart();
        getData(12);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_select_time, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id){
            case R.id.action_12_hour:
                getData(12);
                break;
            case R.id.action_1_day:
                getData(24);
                break;
            case R.id.action_1_week:
                getData(24*7);
                break;
/*            case R.id.action_1_month:
                getData(24*30);
                break;*/
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * 获取温湿度数据
     * @param section 时间间隔，小时
     */
    private void getData(int section){
        Calendar calendarStart = Calendar.getInstance();
        Calendar calendarEnd = Calendar.getInstance();
        Long now = System.currentTimeMillis();
        Long oneHourBefore = now - 1000*60*60*section;
        calendarStart.setTimeInMillis(oneHourBefore);
        calendarEnd.setTimeInMillis(now);

        presenter.loadSectionTemp(deviceId,
                new Date(calendarStart.getTimeInMillis()),
                new Date(calendarEnd.getTimeInMillis()));

        presenter.loadSectionHum(deviceId,
                new Date(calendarStart.getTimeInMillis()),
                new Date(calendarEnd.getTimeInMillis()));
    }

    private void initTempChart(){

        Description description = new Description();
        description.setText("温度变化情况");

        description.setPosition(620f, 600f);
        description.setTextSize(12);
        lcTempTrend.setDescription(description);
        lcTempTrend.setNoDataText("暂时尚无数据");
        lcTempTrend.setDrawBorders(false);
        lcTempTrend.setDrawGridBackground(true);
        lcTempTrend.setGridBackgroundColor(Color.WHITE & 0x70FFFFFF);
        lcTempTrend.setTouchEnabled(true);
        lcTempTrend.setDragEnabled(true);// 是否可以拖拽
        lcTempTrend.setScaleEnabled(true);// 是否可以缩放


        lcTempTrend.setData(timeLineData);

        Legend mLegend = lcTempTrend.getLegend(); // 设置比例图标示，就是那个一组y的value的

        mLegend.setForm(Legend.LegendForm.CIRCLE);// 样式
        mLegend.setFormSize(6f);// 字体
        mLegend.setTextColor(Color.WHITE);// 颜色

        lcTempTrend.animateX(500); // 立即执行的动画,x轴
    }

    private void initHumChart(){
        Description description = new Description();
        description.setText("湿度度变化情况");
        description.setPosition(620f, 600f);
        description.setTextSize(12);

        lcHumTrend.setDescription(description);
        lcHumTrend.setNoDataText("暂时尚无数据");
        lcHumTrend.setDrawBorders(false);
        lcHumTrend.setDrawGridBackground(true);
        lcHumTrend.setGridBackgroundColor(Color.WHITE & 0x70FFFFFF);
        lcHumTrend.setTouchEnabled(true);
        lcHumTrend.setDragEnabled(true);// 是否可以拖拽
        lcHumTrend.setScaleEnabled(true);// 是否可以缩放


        lcHumTrend.setData(humLineData);

        Legend mLegend = lcHumTrend.getLegend(); // 设置比例图标示，就是那个一组y的value的

        mLegend.setForm(Legend.LegendForm.CIRCLE);// 样式
        mLegend.setFormSize(6f);// 字体
        mLegend.setTextColor(Color.WHITE);// 颜色

        lcHumTrend.animateX(500); // 立即执行的动画,x轴
    }

    @Override
    public void showTempChart(List<Temperature> temperatures){
        if(cvTemp.getVisibility() != View.VISIBLE){
            cvTemp.setVisibility(View.VISIBLE);
        }
        this.temperatureList.clear();
        this.temperatureList.addAll(temperatures);

        LineData data = lcTempTrend.getLineData();

        //y轴数据
        Temperature temperature;
        ArrayList<Entry> yValues = new ArrayList<>();
        for(int i=0; i < temperatureList.size(); i++){
            temperature = temperatureList.get(i);
            yValues.add(new Entry(i, temperature.getTemperature()));
        }

        IAxisValueFormatter timeSection = new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                String str = "NaN";
                if(value < temperatureList.size()){
                    str = temperatureList.get((int)value).getTime();
                    String md = str.substring(5, 10);  //月日
                    String hm = str.substring(11, 16);  //小时分
                    return /*md+"\n"+*/hm;
                }
                return str;
            }
        };

        XAxis xAxis = lcTempTrend.getXAxis();
        xAxis.setGranularity(1f); // minimum axis-step (interval) is 1
        xAxis.setValueFormatter(timeSection);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAvoidFirstLastClipping(true);//图表将避免第一个和最后一个标签条目被减掉在图表或屏幕的边缘

        LineDataSet tempLine = new LineDataSet(yValues, "测试折线图" /*显示在比例图上*/);
        tempLine.setLineWidth(1.75f); // 线宽
        tempLine.setCircleSize(3f);// 显示的圆形大小
        tempLine.setColor(getResources().getColor(R.color.colorPrimary));// 显示颜色
        tempLine.setCircleColor(getResources().getColor(R.color.colorAccent));// 圆形的颜色
        tempLine.setHighLightColor(Color.WHITE); // 高亮的线的颜色

        data.addDataSet(tempLine);

        lcTempTrend.notifyDataSetChanged();
        lcTempTrend.invalidate();
        lcTempTrend.setVisibleXRangeMaximum(10);
        lcTempTrend.setVisibleXRangeMinimum(1);
        lcTempTrend.moveViewToX(temperatures.size()-1);
    }

    @Override
    public void showHumChart(List<Humidity> humidities){
        if(cvHum.getVisibility() != View.VISIBLE){
            cvHum.setVisibility(View.VISIBLE);
        }
        this.humidityList.clear();
        this.humidityList.addAll(humidities);

        LineData data = lcHumTrend.getLineData();

        //y轴数据
        Humidity humidity;
        ArrayList<Entry> yValues = new ArrayList<>();
        for(int i=0; i < humidityList.size(); i++){
            humidity = humidityList.get(i);
            yValues.add(new Entry(i, humidity.getHumidity()));
        }

        IAxisValueFormatter timeSection = new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                String str = humidityList.get((int)value).getTime();
                String md = str.substring(5, 10);  //月日
                String hm = str.substring(11, 16);  //小时分
                return /*md+"\n"+*/hm;
            }
        };

        XAxis xAxis = lcHumTrend.getXAxis();
        xAxis.setGranularity(1f); // minimum axis-step (interval) is 1
        xAxis.setValueFormatter(timeSection);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAvoidFirstLastClipping(true);//图表将避免第一个和最后一个标签条目被减掉在图表或屏幕的边缘

        LineDataSet humLine = new LineDataSet(yValues, "测试折线图" /*显示在比例图上*/);
        humLine.setLineWidth(1.75f); // 线宽
        humLine.setCircleSize(3f);// 显示的圆形大小
        humLine.setColor(getResources().getColor(R.color.colorPrimary));// 显示颜色
        humLine.setCircleColor(getResources().getColor(R.color.colorAccent));// 圆形的颜色
        humLine.setHighLightColor(Color.WHITE); // 高亮的线的颜色

        data.addDataSet(humLine);

        lcHumTrend.notifyDataSetChanged();
        lcHumTrend.invalidate();
        lcHumTrend.setVisibleXRangeMaximum(10);
        lcHumTrend.setVisibleXRangeMinimum(1);
        lcHumTrend.moveViewToX(humidities.size()-1);
    }

}
